package zxing.activity;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Hashtable;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.virtualapp.R;
import io.virtualapp.abs.ui.VActivity;
import zxing.BitmapUtil;

import static zxing.activity.BeautifyQRActivity.px2dip;

public class CodeDisplayActivity extends VActivity {
    @BindView(R.id.result_img)
    ImageView result_img;
    @BindView(R.id.head_back)
    ImageView head_back;
    @BindView(R.id.head_center_title)
    TextView head_center_title;
    String title;
    @BindView(R.id.button_bc)
    Button button_bc;
    @BindView(R.id.button_bea)
    Button button_bea;
    String str;
    @BindView(R.id.qr_bg)
    LinearLayout qr_bg;
    @BindView(R.id.result_img1)
    ImageView result_img1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_code_display);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        str = intent.getStringExtra("data");
        title = intent.getStringExtra("title");
        if (title.equals("我的名片")) {
            result_img.setVisibility(View.GONE);
            qr_bg.setVisibility(View.VISIBLE);

            result_img1.setImageBitmap(QRCodeUtil.createQRCodeBitmapClors(
                    str,
                    (px2dip(getContext(), 110)),
                    getResources().getColor(R.color.colo6),
                    getResources().getColor(R.color.white)));

            button_bc.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SaveBitmapFromView(qr_bg);
                    Toast.makeText(CodeDisplayActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            result_img.setVisibility(View.VISIBLE);
            qr_bg.setVisibility(View.GONE);
            Create2QR2(str, result_img);
            button_bc.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SaveBitmapFromView(result_img);
                    Toast.makeText(CodeDisplayActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                }
            });
        }
        getView();
    }

    public void getView() {
        head_center_title.setText(title);
        head_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        button_bea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), BeautifyQRActivity.class);
                intent.putExtra("data", str);
                startActivity(intent);
            }
        });
    }

    private void Create2QR2(String urls, ImageView imageView) {
        String uri = urls;
        int mScreenWidth = 0;
        Bitmap bitmap;
        try {
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            mScreenWidth = dm.widthPixels;
            bitmap = BitmapUtil.createQRImage(uri, mScreenWidth,
                    null);//不添加中间图标
//            bitmap = BitmapUtil.createQRImage(uri, mScreenWidth,
//                    BitmapFactory.decodeResource(getResources(), R.mipmap.me));//添加中间图标

            if (bitmap != null) {
                imageView.setImageBitmap(bitmap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public Bitmap SaveBitmapFromView(View view) {
        int w = view.getWidth();
        int h = view.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
//        view.layout(0, 0, w, h);
        c.drawColor(Color.WHITE);
        view.draw(c);
        // 缩小图片
        Matrix matrix = new Matrix();
        matrix.postScale(0.5f, 0.5f); //长和宽放大缩小的比例

        bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
//获取当前时间
        Date date = new Date(System.currentTimeMillis());
//        saveBitmap(bmp, simpleDateFormat.format(date) + ".jpg");
        String str = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + simpleDateFormat.format(date) + ".jpg";

        boolean save = ImageUtils.save(bmp, str, Bitmap.CompressFormat.JPEG);
        ToastUtils.showLong(save ? "保存成功" : "保存失败");
        if (save) {
            String copyFilePath  ;
            if (Build.BRAND.equals("Xiaomi")) { // 小米手机
//            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName;
                copyFilePath = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + TimeUtils.getNowMills() + ".jpg";
            } else {  // Meizu 、Oppo
//                str = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + simpleDateFormat.format(date) + ".jpg";
                copyFilePath = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + TimeUtils.getNowMills() + ".jpg";
//            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + bitName;
            }
            if (FileUtils.copyFile(str,copyFilePath)) {
                FileUtils.delete(str);
            }
            MediaScannerConnection.scanFile(CodeDisplayActivity.this, new String[]{copyFilePath}, null, null);

        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
//                CodeDisplayActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + str)));
//                MediaScannerConnection.scanFile(CodeDisplayActivity.this, new String[]{str}, null, null);
            }
        }, 500);

        return bmp;
    }

    /*
     * 保存文件，文件名为当前日期
     */
    public void saveBitmap(Bitmap bitmap, String bitName) {
        String fileName;
        File file;
        fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName;
//        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
//
//        } else {  // Meizu 、Oppo
//            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + bitName;
//        }
        file = new File(fileName);

        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            // 格式为 JPEG，照相机拍出的图片为JPEG格式的，PNG格式的不能显示在相册中
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
                out.flush();
                out.close();
// 插入图库
                MediaStore.Images.Media.insertImage(this.getContentResolver(), file.getAbsolutePath(), bitName, null);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();

        }
        // 发送广播，通知刷新图库的显示
        this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));
    }
}
